package no.rodland.acc.parsers;

import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.Map;

import no.rodland.acc.db.FetchService;
import no.rodland.acc.model.BankAccount;
import no.rodland.acc.model.BankType;
import no.rodland.acc.db.StoreService;

/**
 * Created by IntelliJ IDEA.
 *
 * @Since: Jun 22, 2010 9:12:57 PM
 * @Author: fmr
 */
public abstract class AbstractBankParser extends AbstractParser {
    Map<String, BankType> banktypes;
    protected StoreService storeService;
    private static final Logger log = Logger.getLogger(AbstractBankParser.class);
    protected BankAccount bankAccount;
    private static final int DEFAILT_BANK_ACCOUNT_ID = 10;

    public AbstractBankParser(FetchService fetchService,
                              StoreService storeService,
                              DateParser dateParser,
                              NumberParser numberParser,
                              TextDateParser textDateParser) {
        super(textDateParser, dateParser, numberParser);
        Map<Integer, BankType> tmpBT = fetchService.getBankTypes();
        banktypes = getBankTypes(tmpBT);
        this.storeService = storeService;
        bankAccount = fetchService.getBankAccounts().get(DEFAILT_BANK_ACCOUNT_ID);
    }

    protected BankType getBankType(String btString) {
        BankType bt = banktypes.get(btString.trim());
        return bt == null ? getNewBankType(btString) : bt;
    }

    private BankType getNewBankType(String name) {
        BankType bt = new BankType(name);
        bt = storeService.store(bt);
        banktypes.put(name, bt);
        return bt;
    }

    private static Map<String, BankType> getBankTypes(Map<Integer, BankType> tmpBT) {
        Map<String, BankType> bts = new HashMap<String, BankType>();
        for (BankType bankType : tmpBT.values()) {
            bts.put(bankType.getName().trim(), bankType);
        }
        return bts;
    }

    @Override
    public boolean isParseble(String line) {
        if (line == null || line.length() == 0) {
            return false;
        }
        if (line.indexOf(headerRowRegexp) != -1) {
            log.trace("Found Header row: " + line);
            return false;
        }
        return true;
    }
}
